// 楼宇列表数组
var buildingContent = [];
$(function () {
  // 楼长制 信息管理按钮 楼宇管理 显示
  $(".houseMasterInformationManagement").on("click", function (event) {
    houseMasterInformationManagementFn();

  });

  var houseMasterInformationManagementFn = _.throttle(function () {
    // event.preventDefault();
    $(".buildingManagement-pop").addClass("is-visible3");
    $(".buildingManagementModal .buildingSwitchBtn-pop").addClass("active");
    $(".personManagementModal .buildingSwitchBtn-pop").addClass("active");
    $(".buildingManagementModal").removeClass("none");
    $(".personManagementModal").addClass("none");
    // $(".buildingManagementModal .personSwitchBtn-pop").removeClass("active");
    // $(".personManagementModal .personSwitchBtn-pop").removeClass("active");
    var n = 1;
    buildSearchContent = '';
    $('#buildingManagementModal .buildingManagementSearchInput').val('');
    $('#buildingManagementModal .pageJump').val('');
    $('#buildingManagementModal .tbodyList').html('');
    buildingManagementPageList(n, buildSearchContent);
    // 清除全选按钮的选择状态
    $('#buildingManagementTableSelectAll').prop('checked', false);

    console.log(this)
  }, 2000);

  // 楼宇管理 页面 关闭
  $(".buildingManagement-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".buildingManagement-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
    }
  });
  // 搜索框中的内容
  var buildSearchContent = '';
  // 楼宇管理 分页
  var buildingManagementPageNum = 1;
  var buildingManagementNumCurr = 1;

  function buildingManagementPageFunc(pageSum, startPageNum) {
    console.log(pageSum);
    if (pageSum <= 1) {
      $('#buildingManagementPageBox .pageJump').hide()
    } else {
      $('#buildingManagementPageBox .pageJump').show()
    }
    Page({
      num: pageSum, //页码数
      startnum: startPageNum, //指定页码
      elem: $('#buildingManagementPage'), //指定的元素
      callback: function (n) { //回调函数
        console.log(n)
        buildingManagementNumCurr = n;
        buildingManagementPageList(n, buildSearchContent);
        // 当翻到下一页时 清除掉 全选按钮的 选中状态
        $("#buildingManagementTableSelectAll").prop("checked", false);
      }
    });
  };
  // 渲染 楼宇管理页面的 列表
  function buildingManagementPageList(n, buildSearchContent) {
    $('#buildingManagementModal .tbodyList').html('');
    var obj = {};
    obj.size = 10;
    obj.page = n - 1;
    obj.address = buildSearchContent;
    var ret = getBuildingListInfo(obj);
    ret.then(function (data) {
      console.log(data);
      var content = data.data.content;
      buildingContent = content;
      buildingManagementPageNum = data.data.totalPages;
      size = data.data.size;
      $('#buildingManagementModal .tbodyList').html('');
      for (var i = 0; i < content.length; i++) {
        var routingNumber = content[i].routingNumber;
        if (!routingNumber) {
          routingNumber = '';
        }

        var uuid = content[i].uuid;
        var totalNumberOfFloors = content[i].totalNumberOfFloors;
        if (totalNumberOfFloors) {
          totalNumberOfFloors = '共' + totalNumberOfFloors + '层';
        }
        var orNotFireStation = content[i].orNotFireStation;
        var colorArr = [];
        if (orNotFireStation == 0) {
          orNotFireStation = '未建设';
          colorArr.push('colorba2a2f');
        } else {
          orNotFireStation = '已建设';
          colorArr.push('color17bf5f');
        }
        var orNotFireControlRoom = content[i].orNotFireControlRoom;
        if (orNotFireControlRoom == 0) {
          orNotFireControlRoom = '未建设';
          colorArr.push('colorba2a2f');
        } else {
          orNotFireControlRoom = '已建设';
          colorArr.push('color17bf5f');
        }
        var orNotChargingStation = content[i].orNotChargingStation;
        if (orNotChargingStation == 0) {
          orNotChargingStation = '未建设';
          colorArr.push('colorba2a2f');
        } else {
          orNotChargingStation = '已建设';
          colorArr.push('color17bf5f');
        }
        var buildingCategory = content[i].buildingCategory;
        var unitCategory = content[i].unitCategory;
        $('#buildingManagementModal .tbodyList').append('<tr><td>' + ((n - 1) * size + i + 1) + '</td><td address="' + content[i].address + '">' + content[i].address + '</td><td>' + totalNumberOfFloors + '</td><td>' + content[i].belongRegion + '</td><td>' + content[i].org.orgName + '</td><td>' + buildingCategoryStrArr[buildingCategory] + '</td><td>' + unitCategoryStrArr[unitCategory] + '</td><td class="' + colorArr[0] + '">' + orNotFireStation + '</td><td class="' + colorArr[1] + '">' + orNotFireControlRoom + '</td><td class="' + colorArr[2] + '">' + orNotChargingStation + '</td><td>' + routingNumber + '</td><td><span class="personInspectionStyle personInspection" address="' + content[i].address + '">巡检记录</span><span class="downLoad">下载</span><span class="seeDetails personManagementAddBtn-target">详情</span><span class="setPosition">定位</span><span class="delBtn" devid="' + content[i].id + '">删除</span><span class="buildingQrcode none buildingQrcode' + uuid + '"></span><a id="download" download="qrcode1.jpg"></a></td></tr>');
      }
      buildingManagementPageFunc(buildingManagementPageNum, n);
    }).catch(function (err) {
      console.log(err);
    });
  }

  // 全选 反选
  $("#buildingManagementTableSelectAll").on("click", function () {
    var allcheck = $("#buildingManagementTableSelectAll").prop("checked");
    $("#buildingManagementModal .tbodyList .check").prop("checked", allcheck);
  });
  // 反选
  $("#buildingManagementModal .tbodyList").on("click", '.check', function () {
    var length1 = $("#buildingManagementModal .tbodyList").find(":checkbox").length;
    var length2 = $("#buildingManagementModal .tbodyList").find(":checked").length;
    if (length1 == length2) {
      $("#buildingManagementTableSelectAll").prop("checked", true);
    } else {
      $("#buildingManagementTableSelectAll").prop("checked", false);
    }
  });


  // 楼宇单个删除
  var buildingDelDevid = '';
  $("#buildingManagementModal .buildingManagementTableBox").on("click", ".delBtn", function () {
    // delete删除楼宇localhost:9092/building/delete/{id} 
    delTipModalFunc('确认删除？');
    buildingDelDevid = $(this).attr("devid");
    console.log(buildingDelDevid, this)

  });
  // 点击确定删除按钮
  $("#delTipModal .delCoonfirmTipConfirm").on("click", function (event) {
    event.preventDefault();
    console.log(buildingDelDevid);
    var len = '';
    $.ajax({
      url: '/building/delete/' + buildingDelDevid,
      type: 'post',
      data: {
        _method: "DELETE"
      },
      dataTpe: "json",
      success: function (res) {
        console.log(res);
        $(".delTipModal").removeClass("is-visible3");
        tipModalFunc('删除成功!');
        len = $('#buildingManagementModal .buildingManagementTableBox .tbodyList tr').length;
        if (len == 1) {
          buildingManagementNumCurr -= 1;
        }
        if (buildingManagementNumCurr < 1) {
          buildingManagementNumCurr = 1;
        }
        buildingManagementPageList(buildingManagementNumCurr, buildSearchContent);

        // buildingManagementPageFunc(buildingManagementPageNum, buildingManagementNumCurr)
      },
      error: function (res) {
        console.log(res);
      }
    });
  });
  // 点击 取消 
  $("#delTipModal .delCoonfirmTipCancel").on("click", function (event) {
    event.preventDefault();
    $(".delTipModal").removeClass("is-visible3");
  });

  //创建二维码
  function buildingCreateQRCode(id, url, width, height, src, label) {
    $('.' + id).empty();
    jQuery('.' + id).qrcode({
      render: 'canvas',
      text: url,
      width: width, //二维码的宽度  
      height: height, //二维码的高度  
      imgWidth: width / 4, //图片宽
      imgHeight: height / 4, //图片高
      src: src, //图片中央的二维码
      ecLevel: 'H', //误差校正水平选择最高级
      mode: 1, //label模式选择2
      label: label,
      fontname: 'Arial',
      fontcolor: '#458fd2',
      background: "#ffffff", //二维码的后景色  
      foreground: "#000", //二维码的前景色  
      typeNumber: -1,
      mSize: 0.019,
      size: 180,
      mPosX: 0.5,
      mPosY: 0.99, //logo 文字的位置
      quiet: 3 // 安静区域 即周边空白区域
    });
  }

  function buildingCodeInit(uuid, qrCodeName) {
    buildingCreateQRCode('buildingQrcode' + uuid, uuid, 180, 180, "img/logo.png", qrCodeName);
  }

  // 楼宇 下载二维码
  $('#buildingManagementModal').on('click', '.downLoad', function () {
    var index = $(this).parents('tr').index();
    var uuid = buildingContent[index].uuid;
    var address = buildingContent[index].communityName + buildingContent[index].buildingName;
    // console.log(uuid,unit, $(this).siblings('.buildingQrcode'),$(this))
    buildingCodeInit(uuid, address);

    $(this).siblings('a').attr('download', address + '.jpg');

    var canvas = $(this).siblings('.buildingQrcode').find("canvas").get(0);
    try { //解决IE转base64时缓存不足，canvas转blob下载
      var blob = canvas.msToBlob();
      navigator.msSaveBlob(blob, 'qrcode.jpg');
    } catch (e) { //如果为其他浏览器，使用base64转码下载
      var url = canvas.toDataURL('image/jpeg');
      $(this).siblings('a').attr('href', url).get(0).click();
    }
    return false;
  });
  // 楼宇信息 添加页面的 删除头像
  $("#buildingManagementInfoAddPage .delTouxiang").on("click", function () {
    $(this).siblings('.pic').attr('src', '');
    multipartFile = {};
    // $(this).siblings('.pic').removeClass('opacity1');
    $("#buildingManagementInfoAddPage .pic").addClass("opacity0");
    // $("#buildingManagementInfoAddPage").find(".addFireStationLogo").addClass("bac");
    var file = $('#buildingManagementInfoAddPage .upload').val('');
    // file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
    //或者
    // file.outerHTML = file.outerHTML; //重新初始化了file的html

  });
  // 楼宇 添加按钮 弹出添加页面
  $(".buildingManagementAddBtn-pop").on("click", function (e) {
    event.preventDefault();
    $(".buildingManagementInfoAddPage-pop").addClass("is-visible3");
    // 添加二维码
    var onlyvalue = (new Date()).valueOf();
    onlyvalue = onlyvalue.toString();
    $('.buildingManagementInfoAddPage .buildingManagementUuid').val(onlyvalue);
    console.log($('.buildingManagementInfoAddPage .buildingManagementUuid').val());
    // createQRCode('qrcodeBMInfoAddPage', 'https://iotss.zjzywl.com/weixin/miniprogram?uuid=' + onlyvalue, "img/logo.png");
    createQRCode('qrcodeBMInfoAddPage', onlyvalue, "img/logo.png");
    // 添加页面 的所属街道
    var ret = getOrganizationList();
    ret.then(function (data) {
      console.log(data);
      $('#buildingManagementInfoAddPage .bMInfoAddPageFormOrgList').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#buildingManagementInfoAddPage .bMInfoAddPageFormOrgList').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>')
      }
      $('#buildingManagementInfoAddPage .bMInfoAddPageFormOrgList').val(localStorage.getItem('userOrgId'));
    }).catch(function (err) {
      onsole.log(err);
    });
    // 将img设置为透明
    $('#buildingManagementInfoAddPage .erweimaBMInfoAddPageBox img').addClass('opacity0');
    $('#buildingManagementInfoAddPage .erweimaBMInfoAddPageBox img').attr('src', '');
  });
  // 楼宇添加页面关闭
  $(".buildingManagementInfoAddPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".buildingManagementInfoAddPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      // 清空数据 
      $('#buildingManagementInfoAddPage').find("input").val('');
      //Modal验证销毁重构
      $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
      $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
      AddBuildingManagementInfoFormValidator();
    }
  });

  //创建二维码
  function createQRCode(id, url, src) {
    $('#' + id).empty();
    jQuery('#' + id).qrcode({
      render: 'canvas',
      text: url,
      background: "#fff", //二维码的后景色  
      foreground: "#000", //二维码的前景色  
      size: 170,
      // quiet: 1 // 安静区域 即周边空白区域
      src: src, //图片中央的二维码
    });
  }

  // 楼宇信息添加页面 点击上传相片
  var picThat;
  var multipartFile;
  var file;
  var imgUpload = 0;
  $("#buildingManagementInfoAddPage .erweimaBMInfoAddPageBox .touxiang").on("click", '.pic', function () {
    console.log(this);
    $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
    $(this).parent().find(".upload").on("change", function (e) {
      imgUpload++;
      console.log(this.files[0]);
      var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
      console.log(objUrl);
      picThat = this;
      console.log(this);
      if (objUrl) {
        $(this).parent().find(".pic").attr("src", objUrl);
        $(this).parent().find(".pic").removeClass('opacity0');
      } else {
        $(this).parent().find(".pic").addClass('opacity0');
      }
    });
  });

  function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) { // basic
      url = window.createObjectURL(file);
    } else if (window.URL != undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  }

  // 楼宇信息 添加  验证form表单
  AddBuildingManagementInfoFormValidator();

  function AddBuildingManagementInfoFormValidator() {
    $("#buildingManagementInfoAddPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        communityName: {
          validators: {
            notEmpty: {
              message: '小区名称不能为空'
            },
            // regexp: {
            //   regexp: /^[0-9]*$/,
            //   message: '楼宇高度只能包含数字'
            // },
            // callback: {
            //   message: '输入格式错误',
            //   callback: function (value) {
            //     console.log(value)
            //     if (!isNaN(value)) { //是否为数字
            //       var patt1 = /^(13[0-9]{8}|14[57][0-9]{8}|15[012356789][0-9]{8}|17[78][0-9]{8}|18[0123456789][0-9]{8}$)/;
            //       if (patt1.test(value)) {
            //         return true;
            //       } else {
            //         //想在手机号验证不通过的时候提示下手机号格式不正确
            //         console.log('cuo')
            //         return false;
            //       }
            //     } 
            //   }
            // }

          }
        },

        latitude: {
          validators: {
            notEmpty: {
              message: '经度不能为空'
            }
          }
        },
        longitude: {
          validators: {
            notEmpty: {
              message: '纬度不能为空'
            }
          }
        },
        buildingName: {
          validators: {
            notEmpty: {
              message: '楼宇名称不能为空'
            }
          }
        },
        totalNumberOfFloors: {
          validators: {
            notEmpty: {
              message: '楼宇高度不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '楼宇高度只能包含数字'
            },
          }
        },
        routingNumber: {
          validators: {
            notEmpty: {
              message: '月需巡检次数不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '月需巡检次数只能包含数字'
            },
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();
      // var building = $("#buildingManagementInfoAddPage .building").val();
      // var unit = $("#buildingManagementInfoAddPage .unit").val();
      // var buildingName = building + '幢' + unit + '单元';
      // // console.log(buildingName);
      // $("#buildingManagementInfoAddPage .buildingName").val(buildingName);
      var building = $('#buildingManagementInfoAddPage .building').val() + '幢';
      var unit = $('#buildingManagementInfoAddPage .unit').val()
      // $('#buildingManagementInfoAddPage .building').val(building);
      if (unit) {
        building = building + unit + '单元';
      }
      $('#buildingManagementInfoAddPage .building').val(building);
      // var $form = $(e.target);
      // console.log($form.serialize());
      // var obj = $form.serialize();
      // console.log(obj);
      // 获取orgId 
      var orgId = $("#buildingManagementInfoAddPage .bMInfoAddPageFormOrgList").val();
      // console.log(orgId);
      var imgSrc = $('#buildingManagementInfoAddPage .touxiang img').attr('src');
      if (imgSrc) {
        // 添加楼宇的时候，没删除图片，则上传
        // 图片上传

        var $form = $(e.target);
        var obj = new FormData($form[0]);

        $.ajax({
          // 1.post添加，修改楼宇localhost:9092/building/save?orgId=1  表单添加Building 
          url: '/building/save?orgId=' + orgId,
          type: 'POST',
          async: false,
          data: obj,
          contentType: false,
          processData: false,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.buildingManagementInfoAddPage-pop').removeClass('is-visible3');
              tipModalFunc('添加成功!');
              // 添加成功后重新渲染
              buildingManagementPageList(buildingManagementNumCurr, buildSearchContent);
              //Modal验证销毁重构
              $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#buildingManagementInfoAddPage').find("input").val('');
              AddBuildingManagementInfoFormValidator();
            } else {
              console.log(result.message);
              $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
              AddBuildingManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
            $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
            AddBuildingManagementInfoFormValidator();

          }
        });
      } else {
        // 添加楼宇的时候，删除图片，则不上传图片
        // var building = $('#buildingManagementInfoAddPage .building').val()+'幢';
        // var unit = $('#buildingManagementInfoAddPage .unit').val()
        // // $('#buildingManagementInfoAddPage .building').val(building);
        // if(unit){
        //   building = building+unit+'单元';
        // }
        // $('#buildingManagementInfoAddPage .building').val(building);
        var $form = $(e.target);
        var obj = $form.serialize();
        console.log(obj);
        $.ajax({
          // 1.post添加，修改楼宇localhost:9092/building/save?orgId=1  表单添加Building 
          url: '/building/save?orgId=' + orgId,
          type: 'POST',
          async: false,
          data: obj,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.buildingManagementInfoAddPage-pop').removeClass('is-visible3');
              tipModalFunc('添加成功!');
              // 添加成功后重新渲染
              buildingManagementPageList(buildingManagementNumCurr, buildSearchContent);
              //Modal验证销毁重构
              $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#buildingManagementInfoAddPage').find("input").val('');
              AddBuildingManagementInfoFormValidator();
            } else {
              console.log(result.message);
              $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
              AddBuildingManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#buildingManagementInfoAddPage").data('bootstrapValidator').destroy();
            $('#buildingManagementInfoAddPage').data('bootstrapValidator', null);
            AddBuildingManagementInfoFormValidator();

          }
        });
      }

    });
  }
  // 楼宇详情弹出
  var buildDetailIndex;
  $("#buildingManagementModal").on("click", '.personManagementAddBtn-target', function (e) {
    event.preventDefault();
    delEditTouxiangFlag = false;
    $(".buildingManagementInfoEditPage-pop").addClass("is-visible3");
    // buildingContent
    buildDetailIndex = $(this).parents('tr').index();
    console.log(buildDetailIndex);
    // 赋值
    $('#buildingManagementInfoEditPage [name="longitude"]').val(buildingContent[buildDetailIndex].longitude);
    $('#buildingManagementInfoEditPage [name="latitude"]').val(buildingContent[buildDetailIndex].latitude);
    $('#buildingManagementInfoEditPage [name="totalNumberOfFloors"]').val(buildingContent[buildDetailIndex].totalNumberOfFloors);
    $('#buildingManagementInfoEditPage [name="communityName"]').val(buildingContent[buildDetailIndex].communityName);
    $('#buildingManagementInfoEditPage [name="address"]').val(buildingContent[buildDetailIndex].address);
    $('#buildingManagementInfoEditPage [name="orgId"]').val(buildingContent[buildDetailIndex].orgId);
    $('#buildingManagementInfoEditPage [name="routingNumber"]').val(buildingContent[buildDetailIndex].routingNumber);

    $('#buildingManagementInfoEditPage [name="belongRegion"]').val(buildingContent[buildDetailIndex].belongRegion);
    $('#buildingManagementInfoEditPage [name="buildingCategory"]').val(buildingContent[buildDetailIndex].buildingCategory);
    $('#buildingManagementInfoEditPage [name="orNotFireStation"]').val(buildingContent[buildDetailIndex].orNotFireStation);
    $('#buildingManagementInfoEditPage [name="unitCategory"]').val(buildingContent[buildDetailIndex].unitCategory);
    $('#buildingManagementInfoEditPage [name="orNotFireControlRoom"]').val(buildingContent[buildDetailIndex].orNotFireControlRoom);
    $('#buildingManagementInfoEditPage [name="orNotChargingStation"]').val(buildingContent[buildDetailIndex].orNotChargingStation);
    $('#buildingManagementInfoEditPage [name="uuid"]').val(buildingContent[buildDetailIndex].uuid);
    console.log(buildingContent[buildDetailIndex].uuid)
    // 禁用
    $('#buildingManagementInfoEditPage input').addClass('disabledStyle');
    $('#buildingManagementInfoEditPage select').addClass('disabledStyle');
    $('#buildingManagementInfoEditPage .buildingNameBox').addClass('disabledStyle');
    $('#buildingManagementInfoEditPage input').attr('disabled', true);
    $('#buildingManagementInfoEditPage select').attr('disabled', true);
    $('#buildingManagementInfoEditPage .buildingEditBtn').show();
    $('#buildingManagementInfoEditPage .buildingManagementInfoAddPageBtn-pop').hide();
    // 展示楼宇图片
    var photoUrl = buildingContent[buildDetailIndex].photoUrl;
    $('#buildingManagementInfoEditPage .oldPhoto').val(photoUrl);
    if (photoUrl) {
      $('#buildingManagementInfoEditPage .erweimaBMInfoAddPageBox img').attr('src', photoUrl);
      $('#buildingManagementInfoEditPage .erweimaBMInfoAddPageBox .pic').parent().find(".pic").removeClass('opacity0');
      // $('#buildingManagementInfoEditPage .erweimaBMInfoAddPageBox input').val(photoUrl);
    } else {
      $('#buildingManagementInfoEditPage .erweimaBMInfoAddPageBox .pic').parent().find(".pic").addClass('opacity0');
    }

    function getCaption(obj) {
      var index = obj.lastIndexOf("幢");
      var index1 = obj.lastIndexOf("单元");
      if (index > 0 && index1 > 0) {
        obj = obj.substring(index + 1, index1);
        //  console.log(obj);
        return obj;
      } else {
        return '';
      }
    }

    function getCaptionBuild(obj) {
      var index = obj.lastIndexOf("幢");
      if (index > 0) {
        obj = obj.substring(0, index);
        return obj;
      } else {
        return '';
      }
    }
    var buildingName = buildingContent[buildDetailIndex].buildingName;
    $('#buildingManagementInfoEditPage .bMInfoAddPageFormBuidlingName .unit').val(getCaption(buildingName));
    $('#buildingManagementInfoEditPage .bMInfoAddPageFormBuidlingName .building').val(getCaptionBuild(buildingName));

    // 楼宇详情页面 的所属街道
    var ret = getOrganizationList();
    ret.then(function (data) {
      console.log(data);
      $('#buildingManagementInfoEditPage .bMInfoAddPageFormOrgList').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#buildingManagementInfoEditPage .bMInfoAddPageFormOrgList').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>')
      }
      $('#buildingManagementInfoEditPage .bMInfoAddPageFormOrgList').val(buildingContent[buildDetailIndex].org.id);
    }).catch(function (err) {
      console.log(err);
    });
    var uuid = buildingContent[buildDetailIndex].uuid;
    // createQRCode('qrcodeBMInfoEditPage', 'https://iotss.zjzywl.com/weixin/miniprogram?uuid=' + uuid, "img/logo.png");
    createQRCode('qrcodeBMInfoEditPage', uuid, "img/logo.png");

  });

  // 修改楼宇信息图片
  $("#buildingManagementInfoEditPage .touxiang").on("click", '.pic', function () {
    console.log(this);
    $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
    $(this).parent().find(".upload").on("change", function (e) {
      imgUpload++;
      console.log(this.files[0]);
      var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
      console.log(objUrl);
      picThat = this;
      console.log(this);
      if (objUrl) {
        $(this).parent().find(".pic").attr("src", objUrl);
        $(this).parent().find(".pic").removeClass('opacity0');
      } else {
        $(this).parent().find(".pic").addClass('opacity0');
      }
    });
  });
  // 删除楼宇详情的图片
  $("#buildingManagementInfoEditPage .delTouxiang").on("click", function () {
    if (delEditTouxiangFlag) {
      $(this).siblings('.pic').attr('src', '');
      $("#buildingManagementInfoEditPage .pic").addClass("opacity0");
      $('#buildingManagementInfoEditPage .upload').val('');
      $('#buildingManagementInfoEditPage .oldPhoto').val('');
    }
  });
  // 修改 楼宇信息
  editBuildingManagementInfoFormValidator();

  function editBuildingManagementInfoFormValidator() {
    $("#buildingManagementInfoEditPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        communityName: {
          validators: {
            notEmpty: {
              message: '小区名称不能为空'
            },
            // regexp: {
            //   regexp: /^[0-9]*$/,
            //   message: '楼宇高度只能包含数字'
            // },
            // callback: {
            //   message: '输入格式错误',
            //   callback: function (value) {
            //     console.log(value)
            //     if (!isNaN(value)) { //是否为数字
            //       var patt1 = /^(13[0-9]{8}|14[57][0-9]{8}|15[012356789][0-9]{8}|17[78][0-9]{8}|18[0123456789][0-9]{8}$)/;
            //       if (patt1.test(value)) {
            //         return true;
            //       } else {
            //         //想在手机号验证不通过的时候提示下手机号格式不正确
            //         console.log('cuo')
            //         return false;
            //       }
            //     } 
            //   }
            // }

          }
        },

        latitude: {
          validators: {
            notEmpty: {
              message: '经度不能为空'
            }
          }
        },
        longitude: {
          validators: {
            notEmpty: {
              message: '纬度不能为空'
            }
          }
        },
        buildingName: {
          validators: {
            notEmpty: {
              message: '楼宇名称不能为空'
            }
          }
        },
        totalNumberOfFloors: {
          validators: {
            notEmpty: {
              message: '楼宇高度不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '楼宇高度只能包含数字'
            },
          }
        },
        routingNumber: {
          validators: {
            notEmpty: {
              message: '月需巡检次数不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '月需巡检次数只能包含数字'
            },
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();
      // var building = $("#buildingManagementInfoEditPage .building").val();
      // var unit = $("#buildingManagementInfoEditPage .unit").val();
      // var buildingName = building + '幢' + unit + '单元';
      // $("#buildingManagementInfoEditPage .buildingName").val(buildingName);
      var building = $('#buildingManagementInfoEditPage .building').val() + '幢';
      var unit = $('#buildingManagementInfoEditPage .unit').val()
      // $('#buildingManagementInfoEditPage .building').val(building);
      if (unit) {
        building = building + unit + '单元';
      }
      $('#buildingManagementInfoEditPage .building').val(building);
      // $('#buildingManagementInfoEditPage [name="uuid"]').val(buildingContent[buildDetailIndex].uuid);
      // $('#buildingManagementInfoEditPage input').removeAttr('disabled');
      var uuid = $('#buildingManagementInfoEditPage [name="uuid"]').val();
      // var $form = $(e.target);
      // var obj = $form.serialize();
      // console.log(obj);
      // 获取orgId 
      var orgId = $("#buildingManagementInfoEditPage .bMInfoAddPageFormOrgList").val();
      var id = buildingContent[buildDetailIndex].id;
      var oldPhoto = $('#buildingManagementInfoEditPage .oldPhoto').val();
      var newPhoto = $('#buildingManagementInfoEditPage .touxiang img').attr('src');
      console.log(oldPhoto, newPhoto, oldPhoto == newPhoto)
      if ((oldPhoto != newPhoto) && (newPhoto != '')) {
        // // 图片上传
        var $form = $(e.target);
        var obj = new FormData($form[0]);
        // console.log(multipartFile);
        console.log(obj);
        $.ajax({
          // 1.post添加，修改楼宇localhost:9092/building/save?orgId=1  表单添加Building 
          url: '/building/save?orgId=' + orgId + '&id=' + id,
          type: 'POST',
          async: false,
          data: obj,
          contentType: false,
          processData: false,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.buildingManagementInfoEditPage-pop').removeClass('is-visible3');
              tipModalFunc('修改成功!');
              // 添加成功后重新渲染
              buildingManagementPageList(buildingManagementNumCurr, buildSearchContent);
              //Modal验证销毁重构
              $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#buildingManagementInfoEditPage').find("input").val('');
              editBuildingManagementInfoFormValidator();
            } else {
              console.log(result.message);
              editBuildingManagementInfoFormValidator();
              $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);
            }
          },
          error: function () {
            editBuildingManagementInfoFormValidator();
            $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
            $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);

          }
        });
      } else {
        var $form = $(e.target);
        var obj = $form.serialize();
        obj = obj + '&photoUrl=' + oldPhoto;
        console.log(obj);
        $.ajax({
          // 1.post添加，修改楼宇localhost:9092/building/save?orgId=1  表单添加Building 
          url: '/building/save?orgId=' + orgId + '&id=' + id,
          type: 'POST',
          async: false,
          data: obj,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.buildingManagementInfoEditPage-pop').removeClass('is-visible3');
              tipModalFunc('修改成功!');
              // 添加成功后重新渲染
              buildingManagementPageList(buildingManagementNumCurr,buildSearchContent);
              //Modal验证销毁重构
              $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#buildingManagementInfoEditPage').find("input").val('');
              editBuildingManagementInfoFormValidator();
            } else {
              console.log(result.message);
              $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);
              editBuildingManagementInfoFormValidator();
            }
          },
          error: function () {
            editBuildingManagementInfoFormValidator();
            $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
            $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);

          }
        });
      }

    });
  }
  // 如果点击了修改按钮则可以删除图片，否则不可以
  var delEditTouxiangFlag = false;
  // 点击修改按钮
  $('#buildingManagementInfoEditPage .buildingEditBtn').on('click', function () {
    $(this).hide();
    $(this).siblings('.buildingManagementInfoAddPageBtn').show();
    $('#buildingManagementInfoEditPage input').removeAttr('disabled');
    $('#buildingManagementInfoEditPage input').removeClass('disabledStyle');
    $('#buildingManagementInfoEditPage select').removeAttr('disabled');
    $('#buildingManagementInfoEditPage select').removeClass('disabledStyle');
    $('#buildingManagementInfoEditPage .buildingNameBox').removeClass('disabledStyle');
    delEditTouxiangFlag = true;
  });

  // 楼宇详情页面关闭
  $(".buildingManagementInfoEditPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".buildingManagementInfoEditPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      $('#buildingManagementInfoEditPage .oldPhoto').val('');
      $('#buildingManagementInfoEditPage .touxiang img').attr('src', '');
      //Modal验证销毁重构
      $("#buildingManagementInfoEditPage").data('bootstrapValidator').destroy();
      $('#buildingManagementInfoEditPage').data('bootstrapValidator', null);
      // 清空数据 
      $('#buildingManagementInfoEditPage').find("input").val('');
      editBuildingManagementInfoFormValidator();
    }
  });
  // 楼宇模糊查询
  buildSearchFunc();

  function buildSearchFunc() {
    //模糊查询
    $('body').on('click', function () {
      $("#buildingManagementModal .searchList").hide();
    });
    var fn = _.debounce(function () {
      $("#buildingManagementModal .searchList").show();

      if ($("#buildingManagementModal .searchList li")) { //键盘抬起后就判断页面中是否存在这个元素,存在就删除
        $("#buildingManagementModal .searchList li").remove();
      }
      buildSearchContent = $("#buildingManagementModal .buildingManagementSearchInput").val();
      buildSearchContent = $.trim(buildSearchContent);
      console.log(buildSearchContent)
      if (buildSearchContent) {
        $.ajax({
          url: "/building/getBuildings?address=" + buildSearchContent + "&size=10&page=0",
          type: "GET",
          async: false,
          success: function (result) {
            console.log(result)
            var data = result.data.content;
            for (var i = 0; i < data.length; i++) {
              $("#buildingManagementModal .searchList").append('<li>' + data[i].address + '</li>');
            }
          }
        });
        $("#buildingManagementModal .searchList").show();
      }

    }, 500);
    $("#buildingManagementModal .buildingManagementSearchInput").on("input", function (e) {
      fn();
    });
    //直接输入地址,点击列表查询
    $("#buildingManagementModal .searchList").on("click", "li", function () {
      $("#buildingManagementModal .searchList").show();
      var liVal = $(this).text();
      liVal = $.trim(liVal);
      var searchVal = $("#buildingManagementModal .buildingManagementSearchInput").val(liVal);
      buildSearchContent = liVal;
      $("#buildingManagementModal .searchList").html(""); //hide
      return false;
    });
  }
  //点击楼宇管理搜索按钮 
  var buildingManagementSearchFn = _.debounce(function () {
    buildingManagementNumCurr = 1;
    buildingManagementPageList(1, buildSearchContent);
  }, 500);
  $("#buildingManagementsearchBtn").on('click', function () {
    buildingManagementSearchFn();
  });
  // ------------------------------人员模块---------------------------------
  // --------------人员列表-----------------


  // --------------人员添加-------------
  // 人员添加页面  添加按钮 弹出添加页面
  $(".personManagementAddBtn-pop").on("click", function (e) {
    event.preventDefault();
    $(".personManagementInfoAddPage-pop").addClass("is-visible3");
    // 添加二维码
    // var onlyvalue = (new Date()).valueOf();
    // onlyvalue = onlyvalue.toString();
    // $('.personManagementInfoAddPage .personManagementUuid').val(onlyvalue);
    // console.log($('.personManagementInfoAddPage .personManagementUuid').val());
    // createQRCode('qrcodeBMInfoAddPage', 'https://iotss.zjzywl.com/weixin/miniprogram?uuid=' + onlyvalue, "img/logo.png");
    // 添加页面 的所属街道
    var ret = getOrganizationList();
    ret.then(function (data) {
      console.log(data);
      $('#personManagementInfoAddPage .bMInfoAddPageFormOrgList').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#personManagementInfoAddPage .bMInfoAddPageFormOrgList').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>')
      }
      $('#personManagementInfoAddPage .bMInfoAddPageFormOrgList').val('66');
    }).catch(function (err) {
      onsole.log(err);
    });

    buildWorkRangeArr = [];
    $('.buildWorkRange-trigger').val('');
    $('.buildWorkRangeItem ul').html('');
    $('#personManagementInfoAddPage .touxiang img').attr('src', '');
    $('#personManagementInfoAddPage .touxiang img').addClass('opacity0');
  });
  var buildingPersonNumCurr = 1;
  // 人员翻页
  function buildingPersonPageFunc(pageSum, startPageNum) {
    console.log(pageSum);
    if (pageSum <= 1) {
      $('#personManagementPageBox .pageJump').hide()
    } else {
      $('#personManagementPageBox .pageJump').show()
    }
    Page({
      num: pageSum, //页码数
      startnum: startPageNum, //指定页码
      elem: $('#personManagementPage'), //指定的元素
      callback: function (n) { //回调函数
        buildingPersonNumCurr = n;
        buildingPersonPageList(n, personSearchContent);
        // 当翻到下一页时 清除掉 全选按钮的 选中状态
        $("#personManagementTableSelectAll").prop("checked", false);
      }
    });
  }

  // 人员列表渲染出来的数组
  var buildingPeopleContent = [];
  // 渲染 人员管理页面的 列表
  function buildingPersonPageList(n, personSearchContent) {
    $('.personManagementTableBox .tbodyList').html('');
    var obj = {};
    obj.size = 11;
    obj.page = n - 1;
    obj.name = personSearchContent;
    var ret = getBuildingPeopleListInfo(obj);
    ret.then(function (data) {
      console.log(data);
      var content = data.data.content;
      buildingPeopleContent = content;
      var buildingPersonPageNum = data.data.totalPages;
      var size = data.data.size;
      $('.personManagementTableBox .tbodyList').html('');
      for (var i = 0; i < content.length; i++) {


        // var uuid = content[i].uuid;
        var operatingPost = content[i].operatingPost;
        if (operatingPost == 0) {
          operatingPost = '单位楼长';
        } else if (operatingPost == 1) {
          operatingPost = '行政楼长';
        } else if (operatingPost == 2) {
          operatingPost = '街道消安办';
        } else if (operatingPost == 3) {
          operatingPost = '街道分管领导';
        }
        var reportingTime = content[i].reportingTime;
        if (reportingTime) {
          reportingTime = moment(reportingTime).format('YYYY-MM-DD HH:mm');
        } else {
          reportingTime = '空';
        }

        // console.log(content[i].id)
        var workingRangeStr = '';
        for (var j = 0; j < content[i].building.length; j++) {
          workingRangeStr = workingRangeStr + content[i].building[j].address + '、';
        }
        workingRangeStr = workingRangeStr.slice(0, workingRangeStr.length - 1);
        var workingRangeStrAll = workingRangeStr;
        // workingRangeStr = '滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢滨江金色海岸7幢';
        if (workingRangeStr.length > 40) {
          workingRangeStr = workingRangeStr.slice(0, 40) + ' . . .';
        }
        // --------------------------------TODO----------------------------
        $('.personManagementTableBox .tbodyList').append('<tr><td>' + ((n - 1) * size + i + 1) + '</td><td>' + content[i].name + '</td><td>' + operatingPost + '</td><td>' + content[i].phoneNumber + '</td><td class="workingRangeBox workingRangeItemBoxStyle"><span class="workingRange workingRangeItemStyle none">' + workingRangeStrAll + '</span><span class="after"></span>' + workingRangeStr + '</td><td>' + reportingTime + '</td><td><span class="personInspectionStyle personInspection" name="' + content[i].name + '" address="' + content[i].address + '">巡检记录</span><span class="seeDetails">详情</span><span class="delBtn" devid="' + content[i].id + '">删除</span></td></tr>'); //<td><input type="checkbox" class="check" devid="' + content[i].id + '"></td>
        // $('.personManagementTableBox .tbodyList').append('<tr><td>' + ((n - 1) * size + i + 1) + '</td><td>' + content[i].name + '</td><td>' + operatingPost + '</td><td>' + content[i].phoneNumber + '</td><td>' + workingRangeStr + '</td><td>' + reportingTime + '</td><td><span class="seeDetails">详情</span></td></tr>'); //<td><input type="checkbox" class="check" devid="' + content[i].id + '"></td>
      }
      buildingPersonPageFunc(buildingPersonPageNum, n);
    }).catch(function (err) {
      console.log(err);
    });
  }

  // 人员工作范围 tip 显示全部信息
  $('#personManagementModal .personManagementTableBox').on("mouseover mouseout", '.workingRangeBox', function (event) {
    var $this = $(this);
    var $workingRange = $this.find('.workingRange');
    var outerHeight = $workingRange.outerHeight();
    if (outerHeight > 30) {
      if (event.type == "mouseover") {
        //鼠标悬浮
        $workingRange.show();
        $workingRange.css('top', -outerHeight + 'px');
        $this.find('.after').show();

      } else if (event.type == "mouseout") {
        //鼠标离开
        $workingRange.hide();
        $this.find('.after').hide();

      }
    }

  });

  // 人员添加 点击上传图片到本地
  $("#personManagementInfoAddPage .touxiang").on("click", '.pic', function () {
    $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
    $(this).parent().find(".upload").on("change", function (e) {
      var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
      if (objUrl) {
        $(this).parent().find(".pic").attr("src", objUrl);
        $(this).parent().find(".pic").removeClass('opacity0');
      } else {
        $(this).parent().find(".pic").addClass('opacity0');
      }
    });
  });
  // 人员信息 添加页面的 删除头像
  $("#personManagementInfoAddPage .delTouxiang").on("click", function () {
    $(this).siblings('.pic').attr('src', '');
    $("#personManagementInfoAddPage .pic").addClass("opacity0");
    $('#personManagementInfoAddPage .upload').val('');
  });


  // 楼长制人员添加
  addpersonManagementInfoFormValidator();

  function addpersonManagementInfoFormValidator() {
    $("#personManagementInfoAddPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        name: {
          validators: {
            notEmpty: {
              message: '姓名不能为空'
            },
            remote: {
              url: '/buildingPeople/validateByName',
              data: {
                'name': $('#personManagementInfoAddPage .name').val(),
              },
              type: 'POST',
              delay: 1000,
              message: "姓名已存在",
            },
          }
        },
        phoneNumber: {
          validators: {
            notEmpty: {
              message: '联系方式不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '联系方式只能包含数字'
            },
          }
        },
        operatingPost: {
          validators: {
            notEmpty: {
              message: '岗位不能为空'
            },
          }
        },
        userName: {
          validators: {
            notEmpty: {
              message: '分管账号不能为空'
            },
            remote: {
              url: '/buildingPeople/validateName',
              data: {
                'userName': $('#personManagementInfoAddPage .userName').val(),
              },
              type: 'POST',
              delay: 1000,
              message: "分管账号已存在",
            },
          }
        },
        passWord: {
          validators: {
            notEmpty: {
              message: '分管密码不能为空'
            },
          }
        },
        workingRange: {
          validators: {
            notEmpty: {
              message: '工作范围不能为空'
            },
          }
        },
        orgId: {
          validators: {
            notEmpty: {
              message: '所属街道不能为空'
            },
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();

      var orgId = $("#personManagementInfoAddPage .bMInfoAddPageFormOrgList").val();
      var $form = $(e.target);
      var imgUrl = $('#personManagementInfoAddPage .touxiang img').attr('src');

      var buildWorkRangeArrSub = [];
      for (var i = 0; i < buildWorkRangeArr.length; i++) {
        var buildWorkRangeObjSub = {};
        buildWorkRangeObjSub.id = buildWorkRangeArr[i].id;
        console.log(i, buildWorkRangeArr[i].id)
        buildWorkRangeArrSub.push(buildWorkRangeObjSub);
      }
      if (imgUrl) {
        var obj = new FormData($form[0]);

        obj.append("workingRange", JSON.stringify(buildWorkRangeArrSub));
        console.log($form.serialize())
        // +'?workingRange='+buildWorkRangeArr
        $.ajax({
          url: '/buildingPeople/save/' + orgId,
          type: 'POST',
          async: false,
          data: obj,
          contentType: false,
          processData: false,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.personManagementInfoAddPage-pop').removeClass('is-visible3');
              tipModalFunc('添加成功!');
              // 添加成功后重新渲染

              buildingPersonPageList(buildingPersonNumCurr, personSearchContent);
              //Modal验证销毁重构
              $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoAddPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#personManagementInfoAddPage').find("input").val('');
              addpersonManagementInfoFormValidator();
              buildWorkRangeArr = [];
              $('.buildWorkRangeItem ul').html('');
            } else {
              console.log(result.message);
              $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoAddPage').data('bootstrapValidator', null);
              addpersonManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
            $('#personManagementInfoAddPage').data('bootstrapValidator', null);
            addpersonManagementInfoFormValidator();

          }
        });
      } else {
        var obj = $form.serialize();
        // obj.append("workingRange", JSON.stringify(buildWorkRangeArr));

        obj = obj + '&workingRange=' + JSON.stringify(buildWorkRangeArrSub);
        console.log(obj)
        // +'?workingRange='+buildWorkRangeArr
        $.ajax({
          url: '/buildingPeople/save/' + orgId,
          type: 'POST',
          async: false,
          data: obj,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.personManagementInfoAddPage-pop').removeClass('is-visible3');
              tipModalFunc('添加成功!');
              // 添加成功后重新渲染
              buildingPersonPageList(buildingPersonNumCurr, personSearchContent);
              //Modal验证销毁重构
              $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoAddPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#personManagementInfoAddPage').find("input").val('');
              addpersonManagementInfoFormValidator();
              buildWorkRangeArr = [];
              $('.buildWorkRangeItem ul').html('');
            } else {
              console.log(result.message);
              $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoAddPage').data('bootstrapValidator', null);
              addpersonManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
            $('#personManagementInfoAddPage').data('bootstrapValidator', null);
            addpersonManagementInfoFormValidator();

          }
        });
      }

    });
  }
  // 人员添加页面关闭
  $(".personManagementInfoAddPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".personManagementInfoAddPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      // 清空数据 
      $('#personManagementInfoAddPage').find("input").val('');
      buildWorkRangeArr = [];
      $('.buildWorkRangeItem ul').html('');

      //Modal验证销毁重构
      $("#personManagementInfoAddPage").data('bootstrapValidator').destroy();
      $('#personManagementInfoAddPage').data('bootstrapValidator', null);
      addpersonManagementInfoFormValidator();
    }
  });

  var personSearchContent = '';
  // 人员模糊查询
  personSearchFunc();

  function personSearchFunc() {
    //模糊查询
    $('body').on('click', function () {
      $("#personManagementModal .searchList").hide();
    });
    var fn = _.debounce(function () {
      $("#personManagementModal .searchList").show();

      if ($("#personManagementModal .searchList li")) { //键盘抬起后就判断页面中是否存在这个元素,存在就删除
        $("#personManagementModal .searchList li").remove();
      }
      personSearchContent = $("#personManagementModal .personManagementSearchInput").val();
      personSearchContent = $.trim(personSearchContent);
      console.log(personSearchContent)

      if (personSearchContent) {
        var obj = {};
        obj.size = 11;
        obj.page = 0;
        obj.name = personSearchContent;
        var ret = getBuildingPeopleListInfo(obj);
        ret.then(function (data) {
          console.log(data);
          var content = data.data.content;
          for (var i = 0; i < content.length; i++) {
            $("#personManagementModal .searchList").append('<li>' + content[i].name + '</li>');
          }
        });

        $("#personManagementModal .searchList").show();
      }

    }, 500);
    $("#personManagementModal .personManagementSearchInput").on("input", function (e) {
      fn();
    });
    //直接输入地址,点击列表查询
    $("#personManagementModal .searchList").on("click", "li", function () {
      $("#personManagementModal .searchList").show();
      var liVal = $(this).text();
      liVal = $.trim(liVal);
      var searchVal = $("#personManagementModal .personManagementSearchInput").val(liVal);
      personSearchContent = liVal;
      $("#personManagementModal .searchList").html(""); //hide
      return false;
    });
  }
  //点击人员管理搜索按钮 
  var personClickSearchFn = _.debounce(function () {
    buildingPersonNumCurr = 1;
    buildingPersonPageList(1, personSearchContent);
  }, 500);
  $("#personManagementSearchBtn").on('click', function () {
    personClickSearchFn();
  });

  // ----------------人员详情页面显示------------------
  var personManagementInfoEditId = '';
  var editDelTouxiangFlag = false;
  $("#personManagementModal .personManagementTableBox").on("click", '.seeDetails', function (event) {
    // event.preventDefault();
    $(".personManagementInfoEditPage-pop").addClass("is-visible3");
    editDelTouxiangFlag = false;
    var index = $(this).parent().parent().index();
    var name = buildingPeopleContent[index].name;
    var phoneNumber = buildingPeopleContent[index].phoneNumber;
    var operatingPost = buildingPeopleContent[index].operatingPost;
    var userName = buildingPeopleContent[index].userName;
    var passWord = buildingPeopleContent[index].passWord;
    var orgId = buildingPeopleContent[index].org.id;
    var headPortraitUrl = buildingPeopleContent[index].headPortraitUrl;
    personManagementInfoEditId = buildingPeopleContent[index].id;
    console.log(headPortraitUrl, buildingPeopleContent[index], operatingPost);

    buildWorkRangeArr = buildingPeopleContent[index].building;

    $('#personManagementInfoEditPage input[name="name"]').val(name);
    $('#personManagementInfoEditPage input[name="phoneNumber"]').val(phoneNumber);
    $('#personManagementInfoEditPage select[name="operatingPost"]').val(operatingPost);
    $('#personManagementInfoEditPage input[name="userName"]').val(userName);
    $('#personManagementInfoEditPage input[name="passWord"]').val(passWord);
    if (headPortraitUrl) {
      $('#personManagementInfoEditPage .oldPhoto').val(headPortraitUrl);
      $('#personManagementInfoEditPage .pic').removeClass('opacity0');
      $('#personManagementInfoEditPage .pic').attr('src', headPortraitUrl);
    } else {
      $('#personManagementInfoEditPage .pic').addClass('opacity0');
    }
    // var buildWorkRangeArr0 = [];
    var buildWorkRangeStr = '';
    var building = buildingPeopleContent[index].building;
    if (building.length > 1) {
      for (var i = 0; i < building.length; i++) {
        // buildWorkRangeArr.push('{"id":' + buildWorkRangeArr[i].id);
        buildWorkRangeStr += building[i].address + '、';
      }
    } else {
      for (var i = 0; i < building.length; i++) {
        // buildWorkRangeArr.push('{"id":' + buildWorkRangeArr[i].id);
        buildWorkRangeStr += building[i].address;
      }
    }

    if (buildWorkRangeStr.length > 9) {
      buildWorkRangeStr = buildWorkRangeStr.slice(0, 9) + '...';
    } else if (buildWorkRangeStr.length < 1) {
      buildWorkRangeStr = '';
    }
    $('#personManagementInfoEditPage .buildWorkRange-trigger').val(buildWorkRangeStr);

    // 添加页面 的所属街道
    var ret = getOrganizationList();
    ret.then(function (data) {
      console.log(data);
      $('#personManagementInfoEditPage .bMInfoAddPageFormOrgList').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#personManagementInfoEditPage .bMInfoAddPageFormOrgList').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>');
      }
      $('#personManagementInfoEditPage .bMInfoAddPageFormOrgList').val(orgId);
    }).catch(function (err) {
      onsole.log(err);
    });
    // 人员详情禁用样式
    $('#personManagementInfoEditPage input').attr('disabled', true);
    $('#personManagementInfoEditPage select').attr('disabled', true);
    $('#personManagementInfoEditPage input').addClass('disabledStyle');
    $('#personManagementInfoEditPage select').addClass('disabledStyle');
    $('#personManagementInfoEditPage .personEditBtn').show();
    $('#personManagementInfoEditPage .personEditSubmit').hide();
  });

  // 人员详情页面关闭
  $(".personManagementInfoEditPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".personManagementInfoEditPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      $('#personManagementInfoEditPage .oldPhoto').val();
      $('#personManagementInfoEditPage .touxiang img').attr('src', '');
      //Modal验证销毁重构
      $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
      $('#personManagementInfoEditPage').data('bootstrapValidator', null);
      // 清空数据 
      $('#personManagementInfoEditPage').find("input").val('');
      editPersonManagementInfoFormValidator();
    }
  });

  // 人员单个删除
  var buildPersonDel;
  $("#personManagementModal .personManagementTableBox").on("click", ".delBtn", function () {
    // delete删除楼宇localhost:9092/building/delete/{id} 
    $('#buildPersonDel').addClass('is-visible3');
    buildPersonDel = $(this).attr("devid");

  });
  // 人员单个删除确定按钮
  $("#buildPersonDel .delConfirm").on("click", function (event) {
    event.preventDefault();
    var len;
    $.ajax({
      url: '/buildingPeople/delete/' + buildPersonDel,
      type: 'post',
      data: {
        _method: "DELETE"
      },
      dataTpe: "json",
      success: function (res) {
        console.log(res);
        $("#buildPersonDel").removeClass("is-visible3");
        tipModalFunc('删除成功!');
        len = $('#personManagementModal .personManagementTableBox .tbodyList tr').length;
        if (len == 1) {
          buildingPersonNumCurr -= 1;
        }
        if (buildingPersonNumCurr < 1) {
          buildingPersonNumCurr = 1;
        }
        console.log(len, buildingPersonNumCurr)
        buildingPersonPageList(buildingPersonNumCurr, personSearchContent);
      },
      error: function (res) {
        console.log(res);
      }
    });
  });
  // 点击 取消 
  $("#buildPersonDel .delCancel").on("click", function (event) {
    event.preventDefault();
    $("#buildPersonDel").removeClass("is-visible3");
  });

  // 人员修改 点击上传图片到本地
  $("#personManagementInfoEditPage .touxiang").on("click", '.pic', function () {
    console.log(this);
    $(this).parent().find(".upload").click(); //隐藏了input:file样式后，点击头像就可以本地上传
    $(this).parent().find(".upload").on("change", function (e) {
      console.log(this.files[0]);
      var objUrl = getObjectURL(this.files[0]); //获取图片的路径，该路径不是图片在本地的路径
      console.log(objUrl);
      console.log(this);
      if (objUrl) {
        $(this).parent().find(".pic").attr("src", objUrl);
        $(this).parent().find(".pic").removeClass('opacity0');
      } else {
        $(this).parent().find(".pic").addClass('opacity0');
      }
    });
  });
  // 人员信息 修改页面的 删除头像
  $("#personManagementInfoEditPage .delTouxiang").on("click", function () {
    console.log(editDelTouxiangFlag)
    if (editDelTouxiangFlag) {
      $(this).siblings('.pic').attr('src', '');
      $("#personManagementInfoEditPage .pic").addClass("opacity0");
      $('#personManagementInfoEditPage .upload').val('');
      $('#personManagementInfoEditPage .oldPhoto').val('');
    }

  });
  // 人员修改按钮
  $('#personManagementInfoEditPage .personEditBtn').on('click', function () {
    // 人员详情禁用样式
    $('#personManagementInfoEditPage input').removeAttr('disabled');
    $('#personManagementInfoEditPage select').removeAttr('disabled');
    $('#personManagementInfoEditPage input').removeClass('disabledStyle');
    $('#personManagementInfoEditPage select').removeClass('disabledStyle');
    $(this).hide();
    $(this).siblings('button').show();
    $('#personManagementInfoEditPage .bv-hidden-submit').remove();
    editDelTouxiangFlag = true;
  });

  // 修改 人员信息提交
  editPersonManagementInfoFormValidator();

  function editPersonManagementInfoFormValidator() {
    $("#personManagementInfoEditPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        name: {
          validators: {
            notEmpty: {
              message: '姓名不能为空'
            },
          }
        },
        phoneNumber: {
          validators: {
            notEmpty: {
              message: '联系方式不能为空'
            },
            regexp: {
              regexp: /^[0-9]*$/,
              message: '联系方式只能包含数字'
            },
          }
        },
        operatingPost: {
          validators: {
            notEmpty: {
              message: '岗位不能为空'
            },
          }
        },
        userName: {
          validators: {
            notEmpty: {
              message: '分管账号不能为空'
            },
          }
        },
        passWord: {
          validators: {
            notEmpty: {
              message: '分管密码不能为空'
            },
          }
        },
        workingRange: {
          validators: {
            notEmpty: {
              message: '工作范围不能为空'
            },
          }
        },
        orgId: {
          validators: {
            notEmpty: {
              message: '所属街道不能为空'
            },
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();
      var building = $("#personManagementInfoEditPage .building").val();
      var unit = $("#personManagementInfoEditPage .unit").val();
      var buildingName = building + '幢' + unit + '单元';
      $("#personManagementInfoEditPage .buildingName").val(buildingName);
      // var $form = $(e.target);
      // var obj = $form.serialize();
      // console.log(obj);
      // 获取orgId 
      var orgId = $("#personManagementInfoEditPage .bMInfoAddPageFormOrgList").val();

      var oldPhoto = $('#personManagementInfoEditPage .oldPhoto').val();
      var newPhoto = $('#personManagementInfoEditPage .touxiang img').attr('src');
      console.log(oldPhoto, newPhoto, oldPhoto == newPhoto)

      var buildWorkRangeArrSub = [];
      for (var i = 0; i < buildWorkRangeArr.length; i++) {
        var buildWorkRangeObjSub = {};
        buildWorkRangeObjSub.id = buildWorkRangeArr[i].id;
        console.log(i, buildWorkRangeArr[i].id)
        buildWorkRangeArrSub.push(buildWorkRangeObjSub);
      }

      if ((oldPhoto != newPhoto) && (newPhoto != '')) {
        // // 图片上传
        var $form = $(e.target);
        var obj = new FormData($form[0]);
        obj.append("workingRange", JSON.stringify(buildWorkRangeArrSub));
        // console.log(multipartFile);
        console.log(obj);
        $.ajax({
          url: '/buildingPeople/save/' + orgId + '?id=' + personManagementInfoEditId,
          type: 'POST',
          async: false,
          data: obj,
          contentType: false,
          processData: false,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.personManagementInfoEditPage-pop').removeClass('is-visible3');
              tipModalFunc('修改成功!');
              // 添加成功后重新渲染
              buildingPersonPageList(buildingPersonNumCurr, personSearchContent);
              //Modal验证销毁重构
              $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoEditPage').data('bootstrapValidator', null);
              // 清空数据 
              buildWorkRangeArr = [];
              $('#personManagementInfoEditPage').find("input").val('');
              editPersonManagementInfoFormValidator();
            } else {
              console.log(result.message);
              $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoEditPage').data('bootstrapValidator', null);
              editPersonManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
            $('#personManagementInfoEditPage').data('bootstrapValidator', null);
            editPersonManagementInfoFormValidator();

          }
        });
      } else {
        var $form = $(e.target);
        var obj = $form.serialize();
        obj = obj + '&headPortraitUrl=' + oldPhoto;
        obj = obj + '&workingRange=' + JSON.stringify(buildWorkRangeArrSub);
        console.log(obj);
        $.ajax({
          url: '/buildingPeople/save/' + orgId + '?id=' + personManagementInfoEditId,
          type: 'POST',
          async: false,
          data: obj,
          success: function (result) {
            console.log(result);
            if (result.status == 200) {
              $('.personManagementInfoEditPage-pop').removeClass('is-visible3');
              tipModalFunc('修改成功!');
              // 添加成功后重新渲染
              buildingPersonPageList(buildingPersonNumCurr, personSearchContent);
              //Modal验证销毁重构
              $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoEditPage').data('bootstrapValidator', null);
              // 清空数据 
              $('#personManagementInfoEditPage').find("input").val('');
              buildWorkRangeArr = [];
              editPersonManagementInfoFormValidator();
            } else {
              console.log(result.message);
              $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
              $('#personManagementInfoEditPage').data('bootstrapValidator', null);
              editPersonManagementInfoFormValidator();
            }
          },
          error: function () {
            $("#personManagementInfoEditPage").data('bootstrapValidator').destroy();
            $('#personManagementInfoEditPage').data('bootstrapValidator', null);
            editPersonManagementInfoFormValidator();

          }
        });
      }

    });
  }


  // --------------------楼宇 人员按钮的切换功能------------------
  // 楼宇
  $(".buildingPersonSwitch").on("click", ".buildingSwitchBtn-pop", function () {
    buildingSwitchBtn();
  });
  var buildingSwitchBtn = _.throttle(function () {
    console.log(this);
    $(".buildingManagementModal .buildingSwitchBtn-pop").addClass("active");
    $(".personManagementModal .buildingSwitchBtn-pop").addClass("active");
    $(".buildingManagementModal").removeClass("none");
    $(".personManagementModal").addClass("none");
    $(".buildingManagementModal .personSwitchBtn-pop").removeClass("active");
    $(".personManagementModal .personSwitchBtn-pop").removeClass("active");
  }, 2000);
  // 人员
  $(".buildingPersonSwitch").on("click", ".personSwitchBtn-pop", function () {
    personSwitchBtnFn();
  });

  var personSwitchBtnFn = _.throttle(function () {
    // 切换
    $(".buildingManagementModal .buildingSwitchBtn-pop").removeClass("active");
    $(".personManagementModal .buildingSwitchBtn-pop").removeClass("active");
    $(".personManagementModal").removeClass("none");
    $(".buildingManagementModal").addClass("none");
    $(".buildingManagementModal .personSwitchBtn-pop").addClass("active");
    $(".personManagementModal .personSwitchBtn-pop").addClass("active");
    $('#buildingManagementModal .personManagementSearchInput').val('');
    personSearchContent = '';
    // 展示人员列表
    buildingPersonPageList(1, personSearchContent);

  }, 2000);



});